package com.wanglibao.woodtrade.woodtrade.model.impl;

import android.content.Context;

import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.model.City;
import com.wanglibao.woodtrade.woodtrade.model.Region;
import com.wanglibao.woodtrade.woodtrade.model.db.BaseDao;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lugg on 2016/5/19.
 */
public class RegionImpl extends BaseDao<Region,String> {
    public RegionImpl(Context context) {
        super(context, Region.class);
    }

    public static String[] getRegionStrings(List<Region> regionList){
        String[] strings = new String[regionList.size()];

        for (int i = 0; i < regionList.size(); i++){
            strings[i] = regionList.get(i).region_name;
        }

        return strings;
    }

    public static void analyCity(Context context,String json) {
        List<Region> regionList = new ArrayList<>();
        List<City> cityList = new ArrayList<>();
        Gson gson = new Gson();
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("list");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String region_type = jsonObject1.getString("region_type");
                if ("1".equals(region_type)) {
                    Region region = gson.fromJson(jsonObject1.toString(), Region.class);
                    regionList.add(region);
                } else {
                    City city = gson.fromJson(jsonObject1.toString(), City.class);
                    cityList.add(city);
                }
            }
            RegionImpl region = new RegionImpl(context);
            region.deleteAll();
            region.insertWithTransaction(regionList);
            CityImpl cityImpl = new CityImpl(context);
            cityImpl.deleteAll();
            cityImpl.insertWithTransaction(cityList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
